import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

typedef FlunetOnChanged(FlunetStatus status);
enum FlunetStatus { none, wifi, wwan }

class Flunet {
  static const MethodChannel _channel = const MethodChannel('flunet');

  final FlunetOnChanged onChanged;
  FlunetStatus status;

  Flunet({this.onChanged}) {
    _channel.setMethodCallHandler(platformCallHandler);
  }

  Future<FlunetStatus> get currentStatus async {
    try {
      int result = await _channel.invokeMethod('status');
      return _covert(result);
    } catch (ignored) {
      print("ignored");
      print(ignored);
    }
  }

  ///实现监听原生方法回调
  Future<FlunetStatus> platformCallHandler(MethodCall call) async {
    print('收到原生回调 ---- ${call.method}= ${call.arguments}, ${this}');
    switch (call.method) {
      case 'didChanged':
        if (onChanged != null) {
          onChanged(_covert(call.arguments));
        }
        break;
    }
  }

  FlunetStatus _covert(int result) {
    FlunetStatus s;
    switch (result) {
      case 1:
        s = FlunetStatus.wifi;
        break;
      case 2:
        s = FlunetStatus.wwan;
        break;
      default:
        s = FlunetStatus.none;
        break;
    }
    return s;
  }
}
